package com.lujianfei.androidthread.threadsActivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.lujianfei.androidthread.R;

import java.lang.ref.WeakReference;

public class HandlerActivity extends AppCompatActivity {

    static final int TYPE_FINISH = 1;
    static final int TYPE_COUNTDOWN = 2;

    MyHandler myHandler; // 定义弱引用 Handler，防止内存泄漏
    TextView txt_info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        myHandler = new MyHandler(this);
        txt_info = findViewById(R.id.txt_info);
        new Thread(){
            @Override
            public void run() {
                // 模拟 3 秒倒计时，走完后调用 activity finish 退出界面
                int count = 3;
                while(count >= 0) {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = myHandler.obtainMessage(); // 通过 obtainMessage 缓存池来获取 Message 可以节省内存开销
                    message.arg1 = TYPE_COUNTDOWN;
                    message.arg2 = count;
                    message.sendToTarget();
                    --count;
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = myHandler.obtainMessage();
                message.arg1 = TYPE_FINISH;
                message.sendToTarget();
            }
        }.start();
    }

    static class MyHandler extends Handler {
        // 持有弱引用HandlerActivity,在合适的时机，GC回收时会被回收掉，避免内存泄漏
        private final WeakReference<HandlerActivity> mActivity;

        public MyHandler(HandlerActivity mainActivity){
            mActivity =new WeakReference<HandlerActivity>(mainActivity);
        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(null != mActivity.get()) {
                switch (msg.arg1) {
                    case HandlerActivity.TYPE_COUNTDOWN : {
                        mActivity.get().txt_info.setText("倒计时: " + msg.arg2);
                    }
                    break;
                    case HandlerActivity.TYPE_FINISH : {
                        mActivity.get().finish();
                    }
                    break;
                }
            }
        }
    }

}
